package com.xiaohei.crm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohei.crm.common.exception.XiaoheiException;
import com.xiaohei.crm.common.result.Result;
import com.xiaohei.crm.dao.*;
import com.xiaohei.crm.mapper.*;
import com.xiaohei.crm.service.RegionService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.xiaohei.crm.common.RedisEnums.REGION_REGISTRY_KEY;
import static com.xiaohei.crm.common.result.ResultCodeEnum.*;

/**
 * ClassName: RegionServiceImpl
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/6/22 10:12
 * Version 1.0
 */
@Service
@RequiredArgsConstructor
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {
    private final CustomerMapper customerMapper;
    private final EnterpriseServicesMapper enterpriseServicesMapper;
    private final InventoryMapper inventoryMapper;
    private final MaterialMapper materialMapper;
    private final UserMapper userMapper;
    private final RegionMapper regionMapper;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<IPage> findByPage() {
        Page<Region> page = new Page<>();
        LambdaQueryWrapper<Region> eq = Wrappers.lambdaQuery(Region.class).eq(Region::getDelFlag, 0);
        return Result.ok(regionMapper.selectPage(page, eq));
    }

    @Override
    public void saveRegion(Region region) {
        String s = stringRedisTemplate.opsForValue().get(REGION_REGISTRY_KEY + region.getId());
        if (StrUtil.isNotEmpty(s)) {
            throw new XiaoheiException(REGION_IS_ALREADY_EXIST);
        }

        int isInsert = baseMapper.insert(region);
        if (isInsert < 1) {
            throw new XiaoheiException(DATA_ERROR);
        }

        stringRedisTemplate.opsForValue()
                .set(REGION_REGISTRY_KEY + region.getId(),region.getArea());
    }

    @Override
    public void updateRegionById(Region region) {
        String s = stringRedisTemplate.opsForValue().get(REGION_REGISTRY_KEY + region.getId());
        if (StrUtil.isEmpty(s)) {
            throw new XiaoheiException(REGION_IS_ALREADY_EXIST);
        }

        LambdaQueryWrapper<Region> eq =
                Wrappers.lambdaQuery(Region.class).eq(Region::getId, region.getId());
        int update = baseMapper.update(region, eq);

        if(update < 1){
            throw new XiaoheiException(DATA_ERROR);
        }
    }

    @Override
    public void removeByRegionId(String id) {
        String s = stringRedisTemplate.opsForValue().get(REGION_REGISTRY_KEY + id);
        if (StrUtil.isEmpty(s)) {
            throw new XiaoheiException(DATA_ERROR);
        }
        //判断关联的角色
        LambdaQueryWrapper<User> userRegionListWq = Wrappers.lambdaQuery(User.class).eq(User::getManagerRegion, id).eq(User::getDelFlag, 0);
        List<User> userList = userMapper.selectList(userRegionListWq);
        List<User> userRegionDatabaseList = userList.stream()
                .filter(user -> user.getManagerRegion().equals(id)).collect(Collectors.toList());
        if(!CollectionUtil.isEmpty(userRegionDatabaseList)){
            throw new XiaoheiException(REGION_HAS_USER_ALREADY_USE);
        }
        //判断关联的设备
        LambdaQueryWrapper<Material> materialLambdaQueryWrapper =
                Wrappers.lambdaQuery(Material.class).eq(Material::getUsageArea, id).eq(Material::getDelFlag, 0);
        List<Material> materialList = materialMapper.selectList(materialLambdaQueryWrapper);
        List<Material> materialUserList = materialList.stream()
                .filter(material -> material.getUsageArea().equals(id)).collect(Collectors.toList());
        if(!CollectionUtil.isEmpty(materialUserList)){
            throw new XiaoheiException(REGION_HAS_MATERIAL_ALREADY_USE);
        }

        //判断关联的库存
        LambdaQueryWrapper<Inventory> inventoryLambdaQueryWrapper =
                Wrappers.lambdaQuery(Inventory.class).eq(Inventory::getInventoryArea, id).eq(Inventory::getDelFlag, 0);
        List<Inventory> inventoryList = inventoryMapper.selectList(inventoryLambdaQueryWrapper);
        List<Inventory> inventoryUserList = inventoryList.stream()
                .filter(material -> material.getInventoryArea().equals(id)).collect(Collectors.toList());
        if(!CollectionUtil.isEmpty(inventoryUserList)){
            throw new XiaoheiException(REGION_HAS_INVENTORY_ALREADY_USE);
        }

        //判断关联的业务
        LambdaQueryWrapper<EnterpriseServices> esLambdaQueryWrapper =
                Wrappers.lambdaQuery(EnterpriseServices.class)
                        .eq(EnterpriseServices::getBusinessRegion, id)
                        .eq(EnterpriseServices::getDelFlag, 0);
        List<EnterpriseServices> esDbList = enterpriseServicesMapper.selectList(esLambdaQueryWrapper);
        List<EnterpriseServices> esList = esDbList.stream()
                .filter(es -> es.getBusinessRegion().equals(id)).collect(Collectors.toList());
        if(!CollectionUtil.isEmpty(esList)){
            throw new XiaoheiException(REGION_HAS_ES_ALREADY_USE);
        }

        //判断关联的客户
        LambdaQueryWrapper<Customer> customerLambdaQueryWrapper =
                Wrappers.lambdaQuery(Customer.class)
                        .eq(Customer::getAttribution, id)
                        .eq(Customer::getDelFlag, 0);
        List<Customer> customerList = customerMapper.selectList(customerLambdaQueryWrapper);
        List<Customer> customers = customerList.stream()
                .filter(customer -> customer.getAttribution().equals(id)).collect(Collectors.toList());
        if(!CollectionUtil.isEmpty(customers)){
            throw new XiaoheiException(REGION_HAS_CUSTOMER_ALREADY_USE);
        }


        LambdaUpdateWrapper<Region> updateWrapper =
                Wrappers.lambdaUpdate(Region.class).eq(Region::getId, id);
        Region region = Region.builder().delFlag(1).build();
        int update = baseMapper.update(region, updateWrapper);

        if(update < 1){
            throw new XiaoheiException(DATA_ERROR);
        }

        stringRedisTemplate.delete(REGION_REGISTRY_KEY + id);
    }
}
